package com.example.bootweb.security;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 请求拦截器，对于非登录的请求进行拦截
 */
@Component
public class MyInterceptor implements HandlerInterceptor {


    @Autowired
    private StringRedisTemplate StringRedisTemplate;

    final String cookieName = "token";

    final String tokenPrefix = "token:";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("之前处理");
        //获取cookie里面的token
        Cookie cookie = getCookie(request, cookieName);
        if (cookie == null){
            redirect(response);
            return false;
        }else {
            String tokenFromRedis = tokenPrefix+cookie.getValue();
            String user = StringRedisTemplate.opsForValue().get(tokenFromRedis);
            if (StringUtils.isEmpty(user)){
                //重定向到登录页
                cookie.setMaxAge(0);
                redirect(response);
                return false;
            }
        }
        return true;
    }

    private Cookie getCookie(HttpServletRequest request, String cookieName){
        Cookie cookie = null;
        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie tmpCookie : cookies) {
                if (tmpCookie.getName().equals(cookieName)) {
                    cookie = tmpCookie;
                }
            }
        }
        return cookie;
    }

    @SneakyThrows
    private void redirect(HttpServletResponse response){
        response.sendRedirect("/login");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("之后处理");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求完成处理");
    }
}
